package com.supor.aiot.common.utils;

import android.util.Base64;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * ---------------------------------------------------------------- <br>
 * Copyright (C) 2014-2020, by het, Shenzhen, All rights reserved.  <br>
 * ---------------------------------------------------------------- <br>
 * <p>
 * 描述: Base64Utils <br>
 * 作者: lei <br>
 * 日期: 2020/9/22 <br>
 */
public class Base64Utils {

    /**
     * 字符Base64加密
     *
     * @param str
     * @return
     */
    public static String encodeToString(String str) {
        return Base64.encodeToString(str.getBytes(StandardCharsets.UTF_8), Base64.DEFAULT);
    }

    /**
     * 字符Base64解密
     *
     * @param str
     * @return
     */
    public static String decodeToString(String str) {
        return new String(Base64.decode(str.getBytes(StandardCharsets.UTF_8), Base64.DEFAULT));
    }

    public static void decoderBase64File(String base64Code, String savePath) {
        base64Code = base64Code.replace("data:image/png;base64,", "");
        byte[] buffer = Base64.decode(base64Code.getBytes(StandardCharsets.UTF_8), Base64.DEFAULT);
        File file = new File(savePath);
        if (file.exists()) {
            boolean b = file.delete();
        }
        try {
            boolean create = file.createNewFile();
            FileOutputStream out = new FileOutputStream(savePath);
            out.write(buffer);
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static byte[] decoderBase64(String base64Code) {
        base64Code = base64Code.replace("data:image/png;base64,", "");
        return Base64.decode(base64Code.getBytes(StandardCharsets.UTF_8), Base64.DEFAULT);
    }
}
